(function(w){
    var postDetails = function () {
        this.Init();
        return this;
    }, c,
        controlScroll = false,alertItem,
        classifyItem = "",
        questionId = getQueryString("objId"),category = getQueryString("category"),
        rpage = 0,reqControl = false,level = 0,
        questionId2 = "",communityId2 = "",category2 = "",
        onlyTop = false,allTop = false,userId = "",
        desc = "",//描述，修改标签需要
        tag = [],//标签数组
        classVal = "",//类别
        sendType = 0,//推送、删除、添加到首页
        openType = 1,//添加到首页用到的类型
        contentCreatedBy = "",//创建者id
        tagName = "",userRole = 1;
        classObj = {"share":"推荐分享","secondhand":"二手闲置","free":"免费赠送","lostAndFound":"失物招领","question":"邻里求助","advertisement":"邻里广告"},//分类对象
        classArray = ["share","secondhand","free","lostAndFound","question","advertisement"];
        tagArrayId = [],//标签id数组
        buttonControlTop = false,buttonControlAllTop = false,buttonControlEssence = false,buttonControlLabel = false,buttonControlClass = false;


    postDetails.prototype = {
        Init: function () {
            c = this;
            //if(sessionStorage.loginData != null && sessionStorage.resUrl != null){
            //    userId = eval( "(" + sessionStorage.loginData + ")").data[0].objId;
            //    //userId = "549968e5bc537bb017000a53";
            //}else{
            //    location.href = "/pages/moderatorManager/html/login.html";//没数据进登录页
            //}

            userId = getQueryString('userId');

            alertItem = new iScroll("alert_list", { "useTransition": true, "vScrollbar": false, "hScroll": false, "onScrollStart": function () {
                controlScroll = true;},
                "onScrollEnd": function () {
                    if(controlScroll){
                        controlScroll = false;
                        var count = Math.round(Math.abs(this.y)/44),y = -count*44;
                        this.scrollTo(0, y, 100);
                        $($("#alert_list li")[count+1]).siblings().removeClass("selected");
                        $($("#alert_list li")[count+1]).addClass("selected");
                        classifyItem = $("#alert_list li")[count+1].innerText;
                        classVal = $("#alert_list li")[count+1].dataset.val;
                    }
                }});

            if(category == "neighbourActivity"){
                $("#add_classify").css("display","none");
                $("#delete").css("display","none");
                $("#add_home").css("width","100%");
                $("footer").css("background","#fff");
                openType = 6;
                tagName = "邻里活动";

                this.data = {"url":"/rest/v1.0/activity/getDetailOfActivity/"+ questionId +"/"+userId+"/opm4mobile"};
                netWork(this.data,this.initData);

                this.rdata = {"url":"/rest/v1.0/activity/getDetailReplyOfActivity/"+ questionId +"/"+rpage+"/"+userId+"/opm4mobile"};
                netWork(this.rdata,this.initReply);
            }else {
                openType = 1;
                tagName = "话题";
                if(category == "share"){
                    //openType = 2;
                    //tagName = "公告";
                }

                this.data = {"url":"/rest/v1.0/Questions/getDetailOfQuestion/"+ questionId +"/"+userId+"/opm4mobile"};
                netWork(this.data,this.initData);

                this.rdata = {"url":"/rest/v1.0/Questions/getDetailReplyOfQuestion/"+ questionId +"/"+rpage+"/"+userId+"/opm4mobile"};
                netWork(this.rdata,this.initReply);
            }

            $("#iscroll")[0].style.height = (document.body.offsetHeight - $("#iscroll")[0].offsetTop - $("footer")[0].offsetHeight)+"px";
            replyList = new iScroll("iscroll", { "useTransition": true, "vScrollbar": false, "hScroll": false, "onScrollStart": function () {
            }, "onScrollEnd": function () {
                if(reqControl && (Math.abs(this.maxScrollY) - Math.abs(this.y) < 100 || this.maxScrollY >= 0)){
                    reqControl = false;
                    //c.rdata = {"url":"/rest/v1.0/Questions/getDetailReplyOfQuestion/"+ questionId +"/"+rpage+"/"+userId+"/opm4mobile","loading": c.listload,"endLoading": c.removeloading};

                    if(category == "neighbourActivity"){
                        c.rdata.url = "/rest/v1.0/activity/getDetailReplyOfActivity/"+ questionId +"/"+rpage+"/"+userId+"/opm4mobile";
                    }else {
                        c.rdata.url = "/rest/v1.0/Questions/getDetailReplyOfQuestion/"+ questionId +"/"+rpage+"/"+userId+"/opm4mobile";
                    }

                    c.rdata.loading = c.listload;
                    c.rdata.endLoading = c.removeloading;
                    netWork(c.rdata,c.initReply);
                }
            }});
        },
        initData: function(data){
            var d = eval( "(" + data + ")"),imagesList = "",
                date = new Date(d.data.dateCreated),lastTime = new Date(d.data.deadline),tag2 = "",initDesc = "";

            initDesc = d.data.desc.length > 30?d.data.desc.substring(0,30)+"...":d.data.desc;
            if(d.data.category == "neighbourActivity"){
                initDesc = "【" + d.data.title + "】" + initDesc;
                if(d.data.activityType == 1){
                    initDesc = "<span style = 'color: #F7744A;'>#团购#</span> " + initDesc;
                }
                $("#name_time").css("width","45%;");
                $(".l-time").css("display","block");
                lastTime = formatTime(lastTime);
                $("#l_time").text(lastTime);
            }

            $("#title_icon")[0].src = sessionStorage.resUrl + d.data.createdBy.images[0].imageURL;
            $("#t_name").text(d.data.createdBy.nickName);
            $("#t_time").text(formatTime(date) + " 发布");
            $("#content").html(initDesc);
            for(var i = 0;i < d.data.images.length;i++){
                imagesList += "<div style = 'background: url("+sessionStorage.resUrl+d.data.images[i].imageURL+") no-repeat center;background-size: 100% auto'></div>";
            }
            $("#img_area").html(imagesList);
            $("#browse").text(d.data.browserCountStr);
            $("#praise").text((d.data.praiseCount?d.data.praiseCount:0));
            $("#replyCount").text((d.data.praiseCount?d.data.replyCountStr:0));
            if(d.data.category) $("#add_classify_item").text(classObj[d.data.category]);
            classVal = d.data.category;
            for(var i = 0;i < classArray.length;i++){
                if(classArray[i] == d.data.category){
                    var y = -i*44;
                    alertItem.scrollTo(0,y,100);
                    $($("#alert_list li")[i+1]).siblings().removeClass("selected");
                    $($("#alert_list li")[i+1]).addClass("selected");
                    break;
                }
            }
            if(d.data.tag && d.data.tag.length > 0){
                tagArrayId = d.data.tag;
                d.data.tag.forEach(function(item){
                    tag2 += item.value+" ";
                    tag.push(item.objId);
                });
                $("#add_label_item").text(tag2);
                $("#selected_label").append(tag2);
            }
            if(d.data.isTop) {$("#only_top img").attr("src","../../images/filter_selected.png"); onlyTop = true;}
            if(d.data.isTopAll) {$("#all_top img").attr("src","../../images/filter_selected.png"); allTop = true;}
            if(d.data.isPrime) {$("#essence img").attr("src","../../images/filter_selected.png"); level = 1;}

            replyList.refresh();
            questionId2 = d.data.objId;
            communityId2 = d.data.community.objId;
            category2 = d.data.category;
            desc = d.data.desc;
            contentCreatedBy = d.data.createdBy.objId;
            if(d.data.createdBy.userType == "talent")userRole = 2;

            //获取标签
            //netWork({"url":"/rest/v1.0/masterData/regions/getDataDictionaryByCategory/02"},c.getLabel);
        },
        initReply: function(data){
            var d = eval( "(" + data + ")"),html = "",date = {};
            $("#comment_title").text(d.data.replyCountStr?d.data.replyCountStr:0);
            if(d.data.replies.length == 0){
                document.getElementById("comment_content").innerHTML += "<li id = 'scroll_tip' style = 'padding: 12px 0;font-size: 14px; color: #ccc;text-align: center;'>没有更多数据了</li>";
                replyList.refresh();
                replyList.scrollTo(0,replyList.maxScrollY,0);
                return;
            }
            d.data.replies.forEach(function(item){
                date = new Date(item.dateReplied);
                html += "<li>"+
                    "<img src = '"+sessionStorage.resUrl + item.repliedBy.images[0].imageURL+"' onerror = 'imgLoadError(this)'>"+
                    "<span class = 'r-name ell'>"+item.repliedBy.nickName+"</span>"+
                    "<span class = 'r-time'>"+formatTime(date)+"</span>"+
                    "<div class = 'clear'></div>"+
                    "<span class = 'r-content'>"+item.replyDesc+"</span>"+
                "</li>";
            });
            $("#comment_content").append(html);
            rpage++;
            reqControl = true;
            replyList.refresh();
        },
        setHandle: function(data){
            var d = eval( "(" + data + ")");

        },
        deletePost: function(data){
            var d = eval( "(" + data + ")");
            if(d.result.status == "1"){
                location.href = "/pages/moderatorManager/html/post/post.html";
            }
        },
        getLabel: function(data){
            var d = eval( "(" + data + ")"),i = 0;
            d.data.forEach(function(item){
                $("#label_list span")[i].dataset.labelId = item.objId;
                $("#label_list span")[i].innerText = item.value;

                for(var j = 0;j < tagArrayId.length;j++){
                    if(tagArrayId[j].objId == item.objId){
                        $("#label_list span")[i].className = "selected";
                        break;
                    }

                }
                i++;
            });
        },
        toHome: function(data){
            var d = eval( "(" + data + ")");
            if(d.result.status == 1) tip.toast("添加首页成功！"); //else tip.toast(message);
        },
        pushHandle: function(data){
            var d = eval( "(" + data + ")");
            if(d.result.status == 1){
                tip.toast("推送成功！");
            }
        },
        listload: function(){
            document.getElementById("comment_content").innerHTML += "<li id = 'scroll_tip' style = 'padding: 12px 0;font-size: 14px; color: #ccc;text-align: center;'>正在加载中...</li>";
            replyList.refresh();
            replyList.scrollTo(0,replyList.maxScrollY,0);
        },
        removeloading: function(){
            document.getElementById("comment_content").removeChild(document.getElementById("scroll_tip"));
            replyList.refresh();
        },
        setLabelHandle: function(data){
            var d = eval( "(" + data + ")");
            //if(d.result.status == 1){
            //    tip.toast("完成设置!");
            //}else{
            //    tip.toast("设置有误！");
            //}
        },
        evt: function(){
            //������һҳ
            $("#back").on("click",function(){
                location.href = "/pages/moderatorManager/html/post/post.html";
            });
            $("#only_top,#all_top,#essence").on("click",function(){
                if(this.id == "only_top"){
                    if(buttonControlTop == false){buttonControlTop = true;}else{buttonControlTop = false;}
                    if($("#only_top img")[0].src.search(/filter_selected/) > 0){
                        $("#only_top img").attr("src","../../images/filter_normal.png");
                        onlyTop = false;
                    }else{
                        $("#only_top img").attr("src","../../images/filter_selected.png");
                        onlyTop = true;
                    }
                }else if(this.id == "all_top"){
                    //if(buttonControlAllTop == false){buttonControlAllTop = true;}else{buttonControlAllTop = false;}
                    //if($("#all_top img")[0].src.search(/filter_selected/) > 0){
                    //    $("#all_top img").attr("src","../../images/filter_normal.png");
                    //    allTop = false;
                    //}else{
                    //    $("#all_top img").attr("src","../../images/filter_selected.png");
                    //    allTop = true;
                    //}
                }else if(this.id == "essence"){
                    if(buttonControlEssence == false){buttonControlEssence = true;}else{buttonControlEssence = false;}
                    if($("#essence img")[0].src.search(/filter_selected/) > 0){
                        $("#essence img").attr("src","../../images/filter_normal.png");
                        level = 0;
                    }else{
                        $("#essence img").attr("src","../../images/filter_selected.png");
                        level = 1;
                    }
                }

            });
            //取消
            $("#push_cancel").on("click",function(){
                $("#content_push").css("display","none");
                $("#mask").css("display","none");
            });
            //推送、删除、添加到首页
            $("#push_confirm").on("click",function(){
                var sendData = {},delDesc = $("#alert_content_textarea").val();

                $("#content_push").css("display","none");
                $("#mask").css("display","none");

                if(sendType == 1){
                    sendData = {"url":"/rest/v1.0/backoffice/Systems/confirmPushByModerator","method":"post","data": "contentId="+questionId+"&communityId="+communityId2+"&tag="+tagName+"&content="+desc+"&type="+1+"&openType="+openType+"&createdBy="+contentCreatedBy+"&desc="+delDesc};
                    netWork(sendData,c.pushHandle);
                }else if(sendType == 2){
                    var formData = new FormData();
                    formData.append("message", delDesc);
                    formData.append("community", communityId2);
                    formData.append("openType", openType);
                    formData.append("contentId", questionId);
                    formData.append("contentCreatedBy", contentCreatedBy);
                    formData.append("type", 2);
                    if(category == "neighbourActivity") formData.append("tag", "活动"); else formData.append("tag", "话题");


                    sendData = {"url":"/rest/v1.0/backoffice/banner/addCommunityBanner","method":"post","formData": formData};
                    netWork(sendData,c.toHome);
                }else if(sendType == 3){
                    tip.confirm({"str":"确定删除吗？","method":function(){
                        sendData = {"url":"/rest/v1.0/Questions/deleteQuestionByModerator","method":"post","data": "questionId="+questionId+"&delDesc="+delDesc};
                        netWork(sendData,c.deletePost);
                    }});
                }
            });

            $("#open_push,#add_home,#delete").on("click",function(){
                if(this.id == "open_push"){
                    $("#alert_content_title")[0].innerText = "推送内容";
                    $("#alert_content_textarea").attr("placeholder","输入一个吸引邻居的推送消息吧");
                    $("#push_confirm").text("推送");
                    sendType = 1;
                }else if(this.id == "add_home"){
                    $("#alert_content_title").text("添加到首页");
                    $("#alert_content_textarea").attr("placeholder","请输入一个吸引邻居的标题吧");
                    $("#push_confirm").text("添加");
                    sendType = 2;
                }else if(this.id == "delete"){
                    $("#alert_content_title").text("删除内容");
                    $("#alert_content_textarea").attr("placeholder","请输入删除的原因");
                    $("#push_confirm").text("删除");
                    sendType = 3;
                }
                $("#content_push").css("display","block");
                $("#mask").css("display","block");
            });

            $("#add_label").on("click",function(){
                $("#label_select").css("transform","translate3d(0,0,0)");
                $("#label_select").css("-webkit-transform","translate3d(0,0,0)");
                buttonControlLabel = true;
            });
            $("#back2").on("click",function(){
                $("#label_select").css("transform","translate3d(-100%,0,0)");
                $("#label_select").css("-webkit-transform","translate3d(-100%,0,0)");
                if($("#selected_label").text() == ""){
                    $("#add_label_item").text("点击添加标签");
                    $("#add_label_item").css("color","#776C6A");
                }else{
                    $("#add_label_item").text($("#selected_label").text());
                    $("#add_label_item").css("color","#000");
                    //tag = $("#selected_label").text().replace(/(\s*$)/g,"").split(" ");//去右边空格
                }
            });
            //$("#label_select")[0].addEventListener("touchmove",function(e){
            //    e.stopPropagation();
            //},false);
            $("#label_list span").on("click",function(){
                var content = this.innerText;
                if(this.className == "selected"){
                    $(this).removeClass("selected");
                    $("#selected_label").text($("#selected_label").text().replace(content+" ",""));
                    for(var i = 0;i< tag.length; i++){
                        if(tag[i] == this.dataset.labelId){
                            tag.splice(i,1);
                            break;
                        }
                    }
                }else{
                    $(this).addClass("selected");
                    $("#selected_label").append(content+" ");
                    tag.push(this.dataset.labelId);
                }
            });

            $("#add_classify").on("click",function(){
                $("#alist").css("display","block");
                $("#mask").css("display","block");
                alertItem.refresh();
                buttonControlClass = true;
                //document.body.scrollTop = 0;
            });

            $("#cancel-item,#confirm-item").on("click",function(){
                $("#alist").css("display","none");
                $("#mask").css("display","none");
                if(this.id == "confirm-item"){
                    $("#add_classify_item").text(classifyItem);
                    $("#add_classify_item2").css("display","none");
                }
            });

            //设置完成
            $("#selected_over").on("click",function(){
                var topData = {},allData = {},levelData = {},labelData = {},classData = {};
                //问题置顶
                if(category != "neighbourActivity"){
                    if(onlyTop){
                        topData = {"url":"/rest/v1.0/backoffice/question/moveQuestionToTop","method":"post","data": "questionId="+questionId2+"&communityId="+communityId2+"&category="+category2,"sync":"false"};
                    }else{
                        topData = {"url":"/rest/v1.0/backoffice/question/cancelTopQuestion","method":"post","data": "questionId="+questionId2+"&category="+category2,"sync":"false"};
                    }
                    if(buttonControlTop) netWork(topData,c.setHandle);

                    //精华帖
                    if(level == 1){
                        levelData = {"url":"/rest/v1.0/backoffice/question/changeQuestionLevel","method":"post","data": "questionId="+questionId2+"&level="+level+"&userRole="+userRole+"&userId="+contentCreatedBy+"&openType=1"+"&desc=您的话题被设为精华"+"&tag=话题","sync":"false"};
                    }else{
                        levelData = {"url":"/rest/v1.0/backoffice/question/changeQuestionLevel","method":"post","data": "questionId="+questionId2+"&level="+level+"&userRole="+userRole+"&userId="+contentCreatedBy,"sync":"false"};
                    }
                    if(buttonControlEssence) netWork(levelData,c.setHandle);
                }else if(category == "neighbourActivity"){//活动置顶
                    if(onlyTop){
                        topData = {"url":"/rest/v1.0/backoffice/activity/moveActivityToTop","method":"post","data": "activityId="+questionId2+"&communityId="+communityId2,"sync":"false"};
                    }else{
                        topData = {"url":"/rest/v1.0/backoffice/activity/cancelTopActivity","method":"post","data": "activityId="+questionId2,"sync":"false"};
                    }
                    if(buttonControlTop) netWork(topData,c.setHandle);

                    //精华帖
                    if(level == 1){
                        levelData = {"url":"/rest/v1.0/backoffice/activity/changeActivityLevel","method":"post","data": "activityId="+questionId2+"&level="+level+"&userRole="+userRole+"&userId="+contentCreatedBy+"&openType=6"+"&desc=您的活动被设为精华并奖励10情值"+"&tag=邻里活动","sync":"false"};
                    }else{
                        levelData = {"url":"/rest/v1.0/backoffice/activity/changeActivityLevel","method":"post","data": "activityId="+questionId2+"&level="+level+"&userRole="+userRole+"&userId="+contentCreatedBy,"sync":"false"};
                    }
                    if(buttonControlEssence) netWork(levelData,c.setHandle);
                }

                //全部置顶
                if(allTop){
                    allData = {"url":"/rest/v1.0/backoffice/activity/moveAllToTop","method":"post","data": "id="+questionId2+"&community="+communityId2,"sync":"false"};
                }else{
                    allData = {"url":"/rest/v1.0/backoffice/activity/cancelTopAll","method":"post","data": "id="+questionId2,"sync":"false"};
                }
                if(buttonControlAllTop) netWork(allData,c.setHandle);

                //修改问题标签
                if(buttonControlLabel && tag.length > 0){
                    if(category != "neighbourActivity"){
                        labelData = {"url":"/rest/v1.0/backoffice/admin/backOfficeUpdateQuestionByModerator/"+questionId,"method":"post","data": "desc="+desc+"&tag="+JSON.stringify(tag).replace(/[\[\]\"\"]/g,""),"sync":"false"};
                    }else{
                        labelData = {"url":"/rest/v1.0/backoffice/activity/backOfficeUpdateActivityServiceByModerator/","method":"post","data": "objId="+questionId+"&tag="+JSON.stringify(tag).replace(/[\[\]\"\"]/g,""),"sync":"false"};
                    }
                    netWork(labelData,c.setLabelHandle);
                }

                //修改选择分类
                if(buttonControlClass && category != "neighbourActivity" && $("#add_classify_item").text() != "点击选择分类"){
                    classData = {"url":"/rest/v1.0/backoffice/question/changeQuestionCategory/"+questionId+"/"+classVal};
                    netWork(classData,c.setClassHandle);
                }

                setTimeout(function(){
                    if(buttonControlTop || buttonControlEssence || buttonControlAllTop || buttonControlLabel || buttonControlClass){
                        tip.toast("设置完成!");
                        buttonControlTop = false;buttonControlEssence = false;buttonControlAllTop = false;buttonControlLabel = false;buttonControlClass = false;
                    }
                },500);
            });


        }
    };
    w.postDetails = postDetails;
})(window)
new postDetails().evt();